package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.Calendar;

/**
 * Returns the day of the year for date, in the range 1 to 366.
 *
 * <pre>
 * mysql> SELECT DAYOFYEAR('2007-02-03');
 *         -> 34
 * </pre>
 *
 * @author jianghang 2014-4-16 下午5:56:59
 * @since 5.0.7
 */
public class Dayofyear extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        java.sql.Timestamp timestamp = Type.TimestampType.convert(args[0]);
        Calendar cal = Calendar.getInstance();
        cal.setTime(timestamp);

        return cal.get(Calendar.DAY_OF_YEAR);
    }

    public Type getReturnType() {
        return Type.LongType;
    }

    public String[] getFunctionNames() {
        return new String[]{"DAYOFYEAR"};
    }
}
